let localtionshowModal = null
import {
	platform,
	channel
} from './platform'
import {
	getSetting
} from './common'

export function showModal({
	content = "检测到您没打开获取位置信息功能权限，是否去设置打开？",
	showCancel = true,
	callback,
	fail
}) {
	if (localtionshowModal) {
		return false;
	}
	localtionshowModal = setTimeout(() => {
		uni.showModal({
			content: content,
			confirmText: '确认',
			cancelText: '取消',
			showCancel: showCancel,
			success: res => {
				if (res.confirm) {
					if (callback && callback instanceof Function) {
						callback()
					}
				} else {
					console.log('取消');
					if (fail && fail instanceof Function) {
						fail()
					}
				}
			},
			complete: () => {
				clearTimeout(localtionshowModal);
				localtionshowModal = null;
			}
		});
	}, 1);
}

export function openSetting({
	callback,
	scope = "scope.userLocation",
	fail,
}) {
	uni.openSetting({
		success: res => {
			if (res.authSetting[scope]) {
				if (callback && callback instanceof Function) {
					callback()
				}
			} else {
				if (fail && fail instanceof Function) {
					fail()
				}
			}
		}
	});
}

export const getLocation = function(callback) {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: 'scope.userLocation',
			success: () => {
				uni.getLocation({
					type: 'gcj02', // 国测局坐标
					success: res => {
						resolve(res)
					},
					fail: err => {
						reject(err)
					}
				});
			},
			fail: err => {
				showModal({
					callback() {
						openSetting({
							scope: "scope.userLocation",
							callback
						})
					}
				});
				// console.log(err);
				reject()
			}
		});
	})
}

export const getWritePhotosAlbum = function() {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: 'scope.writePhotosAlbum',
			success: res => {
				resolve(res)
			},
			fail: err => {
				showModal({
					content: "检测到您没打开保存照片到相册权限，是否去设置打开？",
					callback() {
						openSetting({
							scope: "scope.writePhotosAlbum",
							callback
						})
					}
				});
				// console.log(err);
			}
		});
	})
}

export function wxLogin() {
	return new Promise((resolve, reject) => {
		uni.login({
			// #ifdef APP-PLUS
			provider: 'weixin',
			onlyAuthorize: true,
			// #endif
			success: res => {
				console.log('-----wxLogin success-----', res)
				if (!res.code) {
					uni.showModal({
						content: res.errMsg,
						showCancel: false
					});
					reject(res);
				} else {
					resolve(res.code);
				}
			},
			fail: err => {
				console.log('-----wxLogin fail-----', err)
				let {
					errMsg,
					errCode,
					code
				} = err;

				let title = '登录失败';
				if (errCode === -8) {
					title = '请先安装微信客户端';
				}
				if (platform === '4') {
					uni.showModal({
						content: title,
						showCancel: false
					});
				}
				reject(err);
			},
			
		});
	})
}

export const getCode = function() {
	return new Promise((resolve, reject) => {
		wxLogin().then(code => {
			resolve(code)
		}).catch(err => {
			reject()
		})
	})
}


export const getUserinfo = function(callback) {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: 'scope.userInfo',
			success: () => {
				uni.getUserInfo({
					success: res => {
						resolve(res)
					},
					fail: err => {
						// console.log(err);
						reject(err)
					}
				});
			},
			fail: err => {
				console.log(err);
				showModal({
					content: "检测到您没打开获取用户信息功能权限，是否去设置打开？",
					callback() {
						openSetting({
							callback,
							scope: "scope.userInfo"
						})
					}
				})
				reject()
			}
		});
	})
}

export const authorizeUserinfo = function(scope = "scope.userInfo") {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: scope,
			success: res => {
				uni.getUserInfo({
					success: res => {
						resolve(res)
					},
					fail: err => {
						reject(err)
					}
				});
			},
			fail: err => {
				reject(err)
			}
		});
	})
}


export const authorize = function(scope = "scope.userInfo") {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: scope,
			success: res => {
				resolve(res)
			},
			fail: err => {
				reject(err)
			}
		});
	})
}

/*
 * 打开[ios/安卓]GPS定位权限
 */
export function openGps() {
	let system = uni.getSystemInfoSync(); // 获取系统信息
	if (system.platform === 'android') { // 判断平台
		console.log("安卓平台获取GPS定位权限")
		var context = plus.android.importClass("android.content.Context");
		var locationManager = plus.android.importClass("android.location.LocationManager");
		var main = plus.android.runtimeMainActivity();
		var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
		console.log(mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER))
		if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
			uni.showModal({
				title: '提示',
				content: '请打开定位服务功能',
				showCancel: false, // 不显示取消按钮
				success() {
					var Intent = plus.android.importClass('android.content.Intent');
					var Settings = plus.android.importClass('android.provider.Settings');
					var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
					main.startActivity(intent); // 打开系统设置GPS服务页面

				}
			});
		}
	} else if (system.platform === 'ios') {
		var cllocationManger = plus.ios.import("CLLocationManager");
		var enable = cllocationManger.locationServicesEnabled();
		var status = cllocationManger.authorizationStatus();
		plus.ios.deleteObject(cllocationManger);
		console.log("手机系统的定位没有打开");
		uni.showModal({
			title: '提示',
			content: '请打开定位服务功能',
			showCancel: false, // 不显示取消按钮
			success() {
				var UIApplication = plus.ios.import("UIApplication");
				var application2 = UIApplication.sharedApplication();
				var NSURL2 = plus.ios.import("NSURL");
				var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
				application2.openURL(setting2);
				plus.ios.deleteObject(setting2);
				plus.ios.deleteObject(NSURL2);
				plus.ios.deleteObject(application2);
			}
		});
	}
}

export function saveImageToPhotosAlbum(url){
	uni.hideLoading();
	uni.showLoading({
		title: "保存中"
	});
	uni.saveImageToPhotosAlbum({
		filePath: url,
		success: () => {
			uni.showToast({
				title:'保存成功',
				icon:"none"
			})
		},
		fail: err => {
			console.log("saveImageToPhotosAlbum:fail",err)
			let scope=null
			if(platform==='4'){
				if(channel==='IOS'){
					scope='photoLibrary'
				}else{
					scope='android.permission.WRITE_EXTERNAL_STORAGE'
				}
			}else if(platform==='1'){
				scope='scope.writePhotosAlbum'
			}else if(platform==='3'){
				scope='scope.album'
			}
			let needPermission=false
			if(platform==='4'){
				if (err.errCode == 2) {	// IOS 无权限错误码为2
					needPermission=true
				}else if(err.errCode == 12){// Android 无权限错误码为12
					needPermission=true
				}
			}else if(platform==='1'){
				if (err.errno == 103 ||err.errMsg.indexOf("fail auth deny")!==-1) {
					needPermission=true
				}
			}else if(platform==='3'){
				if (err.errCode == 10200) {
					needPermission=true
				}
			}
			if(needPermission&&scope){
				getSetting(scope, '检测到您没打开保存到相册功能权限，是否去设置打开？', res => {
					saveImageToPhotosAlbum(url);
				});
				return false
			}
			var str = err && err.errMsg;
			if (str && str.indexOf('cancel') != -1) {
				str = '取消保存';
			}
			uni.showToast({
				title:str,
				icon:"none"
			})
		},
		complete: res => {
			uni.hideLoading();
		}
	});
}